package com.example.aoptest.common.aop;

import com.example.aoptest.common.annonation.HasAuth;
import com.example.aoptest.common.constant.GlobalConstant;
import com.example.aoptest.common.token.TokenUtil;
import com.example.aoptest.entity.User;
import jdk.nashorn.internal.parser.Token;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Set;

@Component
@Aspect
public class AuthorityAop {
    @Autowired
    private HttpServletRequest httpServletRequest;



    @Pointcut("@annotation(com.example.aoptest.common.annonation.HasAuth)")
    public void AuthorityAopPointCut() {

    }

    @Around("AuthorityAopPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HasAuth viewRecords = method.getAnnotation(HasAuth.class);
        String idValue = viewRecords.value();
        String token = httpServletRequest.getHeader(GlobalConstant.HEAD_TOKEN);
        User user = TokenUtil.getUser(token);
        Set<String> menuList = user.getMenu();
        if (!menuList.contains(idValue)) {
            throw new RuntimeException("权限不足");
        }
        return joinPoint.proceed();
    }
}
